package com.lin.missyou.api.v1;
import com.lin.missyou.core.DeferReponse;
import com.lin.missyou.dto.ImNoMessageDTO;
import com.lin.missyou.dto.SuccessDTO;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

@RestController
@RequestMapping("/deferredResult")
public class LongPollingTestController {
    //DeferredResult存储在队列中，若同时有多个request1接收到时，request2可以把消息发送给所有的request1请求
    private final Queue<DeferredResult<String>> responseBodyQueue = new ConcurrentLinkedQueue<>();

    @RequestMapping("request1")
    @ResponseBody
    public DeferredResult<DeferReponse<String>> request1(){
        DeferredResult<DeferReponse<String>> result = new DeferredResult<>(10000L); //设置过期时间 10000ms
        result.onTimeout(()->result.setResult(new DeferReponse()));
//        synchronized (responseBodyQueue){
//            responseBodyQueue.add(result);
//        }
        return result;
    }

    @RequestMapping("request2")
    public String request2(String message){
        synchronized (responseBodyQueue){
            responseBodyQueue.forEach(deferredResult -> {
                deferredResult.setResult(message);
                responseBodyQueue.remove(deferredResult);
            });
        }
        return "success";
    }
}
